import React, { PureComponent, useEffect } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, Form, message, Input, Select, InputNumber } from 'antd';
import { TaskModel, TaskUploadStatus } from '@/models/soaTask';
import { useMount, useRequest, useSetState } from 'ahooks';
import { getSeriesModelList } from '@/services/soa/sceneOfficial';
import { checkUploadStatus, setLocalStorage } from '@/utils';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  basicService: state.basicService,
});
interface State {
  [key: string]: any;
}
const useBrandName = (dispatch: any) => {
  // 品牌
  const [brandName, setBrandName] = React.useState<string>(
    localStorage.getItem('tenantCode') || '',
  );

  useEffect(() => {
    dispatch({
      type: 'vehicleInfoQuery/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (e: any) => {
        if (e?.data?.[0]?.brandName) {
          setBrandName(e?.data?.[0]?.brandName);
        }
      },
    });
  }, []);

  return [brandName, setBrandName];
};
const _ImportModal: React.FC = (props: any) => {
  const { formData, modalVisible, checkList, basicService, dispatch } = props;
  const formRef = React.useRef<FormInstance>();
  const [brandName] = useBrandName(dispatch);
  const [state, setState] = useSetState<State>({
    loading: false,
    seriesModelList: [],
    vehicleList: [],
    confirmFlag: false,
    checkMessage: '',
  });
  const { loading, seriesModelList, vehicleList, confirmFlag } = state;
  const handleSubmit = () => {
    formRef.current?.submit();
  };

  const onFinish = (values: any) => {
    const { dispatch } = props;
    let postData = {
      seriesCode: values.seriesCode,
      // modelList: values.modelList,
      socVersion: `V${values.version1}.${values.version2}`,
      serviceContent: checkList.map((t: any) => {
        return {
          serviceId: String(t.id),
          interfaceIds: (t.children ?? []).map((y: any) => String(y.id)),
        };
      }),
    };

    const submitData = {
      ...postData,
      modelList: values.modelList,
      seriesName: seriesModelList.find(t => t.value === values.seriesCode)?.label,
    };
    if (!confirmFlag) {
      setState({
        loading: true,
      });
      let dType = 'basicService/postObjWithRes';
      let url = '/api/ms-soa-service/v1/service/library/service/submitCheck'; //校验
      Promise.allSettled(
        values.modelList.map(t => {
          return dispatch({
            type: dType,
            payload: {
              url: url,
              ...postData,
              modelCode: t.value,
            },
            callback: (res: any) => {},
          });
        }),
      )
        .then(resArr => {
          let statusMessage = '';
          if (
            resArr.some(t => {
              statusMessage = t.value?.statusMessage;
              return t.value?.statusCode === '40060500';
            })
          ) {
            setState({
              confirmFlag: true,
              checkMessage:
                statusMessage ?? '检测到存在未发布服务，确认导入后将覆盖，是否确认导入？',
            });
          } else if (resArr.every(t => t.value?.statusCode === '0')) {
            submitHandel(submitData);
          }
        })
        .finally(() => setState({ loading: false }));

      // .finally(() =>
      //   setState({
      //     loading: false,
      //   }),
      // );
    } else {
      submitHandel(submitData);
    }
  };
  const submitHandel = async data => {
    const { dispatch } = props;
    const tasks: TaskModel['state']['tasks'] = [];
    const reqList = data.modelList.map((t, index) => {
      tasks.push({
        id: (index + 1).toString(),
        brandCode: brandName as string,
        brandName: brandName as string,
        seriesCode: data.seriesCode,
        seriesName: data.seriesName,
        modelCode: t.value,
        modelName: t.label,
        version: data.socVersion,
        status: 1,
      });
      return {
        seriesCode: data.seriesCode,
        modelCode: t.value,
        socVersion: data.socVersion,
        serviceContent: data.serviceContent,
        id: (index + 1).toString(),
      };
    });
    close();
    // 添加任务列表
    dispatch({
      type: 'task/addTasks',
      payload: tasks,
    });

    //开始任务
    let index = 0;
    for (const req of reqList) {
      setLocalStorage('uploadStatus', 'pending');
      dispatch({
        type: 'task/updateTaskStatus',
        payload: {
          taskId: req.id,
          newStatus: 2, //导入中
          disabled: true,
        },
      });
      const { id, ...reset } = req;
      const res = await dispatch({
        type: 'basicService/postObjWithRes',
        payload: {
          url: '/api/ms-soa-service/v1/service/library/service/submit',
          ...reset,
        },
        callback: res => {
          if (res.statusCode === '0') {
          }
        },
      });
      index++;
      if (res?.statusCode === '0') {
        dispatch({
          type: 'task/updateTaskStatus',
          payload: {
            taskId: req.id,
            newStatus: 3, //成功
            disabled: index === reqList.length ? false : true,
          },
        });
      }
    }
    dispatch({
      type: 'task/updateAllTaskStatus',
    });
  };
  const close = (refresh = false) => {
    const { closeModal } = props;
    setState({ comfirmFlag: false, checkMessage: '' });
    formRef.current && formRef.current.resetFields();
    closeModal(refresh);
  };

  const seriesModelChange = (v: any) => {
    const _vehicleList = seriesModelList.find((t: any) => t.value === v).children ?? [];
    setState({
      vehicleList: _vehicleList.map((t: any) => ({ ...t, label: t.name, value: t.code })),
    });
    formRef.current?.setFieldValue('modelList', undefined);
  };

  const footer = (
    <div>
      <Button
        size="small"
        onClick={() => {
          if (confirmFlag) {
            return setState({ confirmFlag: false });
          }
          close();
        }}
      >
        取消
      </Button>
      <Button size="small" loading={loading} onClick={handleSubmit} type="primary">
        确定
      </Button>
    </div>
  );
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: {
        span: 6,
        // offset: 4,
      },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: {
        span: 14,
      },
      md: { span: 16 },
    },
  };
  useMount(() => {
    getSeriesModelList().then(res => {
      if (res.statusCode === '0') {
        setState({
          seriesModelList: (res.data ?? []).map((t: any) => ({
            ...t,
            label: t.name,
            value: t.code,
          })),
        });
      }
    });
  });

  return (
    <Modal
      title={confirmFlag ? '是否确认导入' : '请选择车系车型和服务矩阵版本号'}
      footer={footer}
      visible={modalVisible}
      width={600}
      onCancel={() => close()}
    >
      <Form
        hidden={confirmFlag}
        {...formItemLayout}
        style={{ marginTop: 12 }}
        ref={formRef}
        onFinish={onFinish}
      >
        <FormItem
          label="车系"
          name="seriesCode"
          rules={[
            {
              required: true,
              message: '请选择车系',
            },
          ]}
        >
          <Select onChange={seriesModelChange} placeholder="请选择车系" options={seriesModelList} />
        </FormItem>
        <FormItem
          label="车型"
          name="modelList"
          rules={[
            {
              required: true,
              message: '请选择车型',
            },
          ]}
        >
          <Select
            labelInValue
            allowClear
            mode="tags"
            optionFilterProp="label"
            placeholder="请选择车型"
            options={vehicleList}
          />
        </FormItem>
        <FormItem
          label="服务矩阵版本号"
          dependencies={['version1', 'version2']}
          name={'version'}
          rules={[
            {
              required: true,
              validator(rule, value, callback) {
                const values = formRef.current?.getFieldsValue(['version1', 'version2']);
                if (!Number.isInteger(values.version1) || !Number.isInteger(values.version2))
                  return callback('请输入版本');
                callback();
              },
            },
          ]}
        >
          <Input.Group>
            V&nbsp;
            <Form.Item name={'version1'} noStyle>
              <InputNumber min={0} step={1} precision={0} style={{ width: 100 }} placeholder="" />
            </Form.Item>
            &nbsp;-&nbsp;
            <Form.Item
              name={'version2'}
              // rules={[{ pattern: /^[\d\.]*$/, message: '输入不规范' }]}
              noStyle
            >
              <InputNumber
                min={0}
                step={1}
                precision={0}
                style={{ width: '50%', float: 'none', display: 'inline-block' }}
                placeholder="请输入版本"
              />
            </Form.Item>
          </Input.Group>
        </FormItem>
        <FormItem label="已选服务数量">
          {checkList.length}/{basicService.pageData.pagination?.total}
        </FormItem>
      </Form>
      {confirmFlag ? state.checkMessage : null}
    </Modal>
  );
};
export const ImportModal = connect(mapStateToProps)(_ImportModal);
